/**
 * @Description: 页面第一次加载loading
 * @author kouyl
 * @date 2021/2/19
 */
import React, {useEffect, useRef, useState} from "react";
import Taro, {useDidHide, useDidShow} from "@tarojs/taro";


const runStatusMap = {
  enable: 1,
  disable: 2
}

const PageLoadLoading = ({WrappedComponent = "", params: {once = false}, ...passThroughProps}) => {
  const {global} = passThroughProps?.loading
  const runStatus = useRef(runStatusMap.disabled)
  const [timer, setTimer] = useState();

  // 延时执行
  const debounceDelay = (fn, delay) => {
    return (...args) => {
      clearTimeout(timer)
      setTimer(
        setTimeout(() => {
          fn.apply(this, args);
        }, delay)
      )
    };
  };

  // 避免长时间转圈圈
  const manualDelayHideLoading = debounceDelay(() => {
    Taro.hideLoading()
    if (once) {
      runStatus.current = runStatusMap.disable
    }
  }, 5000)

  // 页面隐藏执行
  useDidHide(() => {
    Taro.hideLoading()
    clearTimeout(timer)
    setTimer(null)
    runStatus.current = runStatusMap.disable
  })

  useDidShow(() => {
    if (!once) {
      runStatus.current = runStatusMap.enable
      manualDelayHideLoading()
    }
  })

  useEffect(() => {
    runStatus.current = runStatusMap.enable
    Taro.showLoading({title: "正在加载中"})
    manualDelayHideLoading()

    return () => {
      Taro.hideLoading()
      runStatus.current = runStatusMap.disable
    }
  }, [])


  useEffect(() => {

    setTimeout(() => {

      if (runStatus.current === runStatusMap.enable) {
        if (global) {
          Taro.showLoading({title: "正在加载中"})
          clearTimeout(timer)
          setTimer(null)
        }

        if (!global) {
          Taro.hideLoading()
          manualDelayHideLoading()
        }
      }

    })
  }, [global])


  return (
    <WrappedComponent {...passThroughProps} />
  )
}

export default PageLoadLoading;


export function WrapPageLoadLoading(WrappedComponent, params = {}) {
  return props =>
    <PageLoadLoading {...props}
      params={params}
      WrappedComponent={WrappedComponent}
    />
}
